package com.tianyu.java.Server.Handler;

import com.tianyu.java.Server.CommonDataTool;
import com.tianyu.java.Server.SmartHomeContextTool;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.StandardSocketOptions;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

/**
 * 描述: 智能家居系统接受客户端链接的回调函数
 */
public class SmartHomeAcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> {

    @Override
    public void completed(AsynchronousSocketChannel socketChannel, AsynchronousServerSocketChannel attachment) {
        try {
            //设置TCP的参数，作用目前为止不知道
            socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
            socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 1024);
            socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 1024);
            //设置读取数据的回调
            if(socketChannel.isOpen()) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                byteBuffer.clear();
                socketChannel.read(byteBuffer, byteBuffer, new SmartHomeReadHandler(socketChannel));
            }
            //设置到通用数据媒介
            //连接成功以后，发送一个指令激活下位机
            byte[] result = {(byte) 0xef, 0x77, 0x00};
            socketChannel.write(ByteBuffer.wrap(result), null, new SmartHomeWriteHandler());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //让服务器继续接受其他请求
            attachment.accept(attachment, this);
        }
    }

    @Override
    public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
        System.out.println("监听失败了");
        try {
            exc.printStackTrace();
        }finally {
            //让服务器继续接受其他请求
            attachment.accept(attachment, this);
        }
    }

    /**
     * 获取客户机的IP
     */
    public String getOnlyIP(String Url) {
        StringBuffer resultIP = new StringBuffer("");
        int start = -1;
        int end = -1;
        byte[] chs = Url.getBytes();
        for(int i = 0; i < chs.length; i++) {
            if (start==-1 && (chs[i]>='0' && chs[i]<='9')) {
                start = i;
            }
            if (chs[i] == ':') {
                end = i;
            }
        }
        if(start!=-1 && end!=-1) {
            resultIP.append(Url, start, end);
        }
        return resultIP.toString();
    }

    /**
     * 获取指定IP的Mac地址
     * */
    public String getMacAddress(String host) throws Exception {
        return "";
    }

}
